package com.grt.admin.controller;

import java.io.File;
import java.util.Date;
import java.util.List;

import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.grt.admin.AdminConstants;
import com.grt.admin.domain.Article;
import com.grt.admin.domain.ArticleType;
import com.grt.admin.domain.dto.ArticleDTO;
import com.grt.admin.domain.dto.ArticleTypeDTO;
import com.grt.admin.service.ArticleService;
import com.grt.admin.util.ArticleTypeQuery;
import com.grt.common.BaseVo;
import com.grt.common.config.SystemConfig;
import com.grt.common.convert.impl.ArticleDOConvertDTO;
import com.grt.common.convert.impl.ArticleDTOConvertDO;
import com.grt.common.convert.impl.ArticleTypeDTOConvertDO;
import com.grt.common.exception.WebException;
import com.grt.common.util.FileUtil;
import com.grt.common.util.StringUtil;
import com.grt.common.util.UserUtil;
import com.grt.file.FileConstants;
import com.grt.file.domain.Appendix;
import com.grt.file.service.AppendixService;
import com.grt.user.domain.User;

@Controller
@RequestMapping(value = "/article")
public class ArticleController {

	@Autowired
	private ArticleService articleService;

	@Autowired
	private AppendixService appendixService;

	@Autowired
	private SystemConfig systemConfig;

	@Autowired
	private ArticleDTOConvertDO articleDTOConvertDO;

	@Autowired
	private ArticleTypeDTOConvertDO articleTypeDTOConvertDO;

	@Autowired
	private ArticleDOConvertDTO articleDOConvertDTO;

	private static final Logger logger = LoggerFactory.getLogger(ArticleController.class);

	@GetMapping("/addArticle")
	public String addArticle(ModelMap modelMap) throws WebException {
		// 1.获取分类信息
		List<ArticleType> types = articleService.getArticleTypeList(new ArticleTypeQuery());
		modelMap.addAttribute("types", types);
		return "admin/addArticle";
	}

	@GetMapping("/addArticleType")
	public String addArticleType(ModelMap modelMap, @RequestParam(defaultValue = "0") long id) throws WebException {
		if (id == 0) {
			modelMap.addAttribute("articleType", new ArticleType());
			return "admin/addArticleType";
		}

		ArticleType articleType = articleService.getArticleTypeById(id);
		if (null != articleType) {
			modelMap.addAttribute("articleType", articleType);
		}

		return "admin/addArticleType";
	}

	/**
	 * 保存信息
	 * 
	 * @param oArticleDTO
	 *            在C层使用DTO对象来校验属性
	 * @return
	 * @throws WebException
	 */
	@ResponseBody
	@PostMapping("/saveArticle")
	public BaseVo<Article> saveArticle(@Valid ArticleDTO oArticleDTO) throws WebException {

		BaseVo<Article> vo = new BaseVo<Article>();

		Article oArticle = articleDTOConvertDO.convert(oArticleDTO);

		// 获取当前登录用户
		User curUser = UserUtil.getLoginUser();
		if (curUser == null) {
			throw new WebException("无法获取当前登录用户");
		}

		// 处理附件图片
		String file = oArticleDTO.getFilename();
		Appendix oAppendix = appendixService.getAppendix(file);
		oAppendix.setAppFile(file);
		oAppendix.setAppDesc(file);
		oAppendix.setAppFileType(FileConstants.FILETYPE_PIC);
		oAppendix.setCreateTime(new Date());
		oAppendix.setCreateUserId(curUser.getId());
		oAppendix.setCreateUsername(curUser.getUsername());
		long appendixid = appendixService.saveAppendix(oAppendix);

		oArticle.setAppendixid(appendixid);

		oArticle.setCrtime(new Date());

		oArticle = articleService.saveArticle(oArticle);

		vo.setDatas(oArticle);

		return vo;
	}

	@RequestMapping("/articlelist")
	public String articlelist(ModelMap modelMap, Integer pageindex, Integer pagesize) throws WebException {
		pageindex = pageindex == null ? AdminConstants.DEF_PAGEINDEX : pageindex;
		pagesize = pagesize == null ? AdminConstants.DEF_PAGESIZE : pagesize;
		System.out.println(pageindex + "|" + pagesize);
		Page<Article> page = articleService.getArticleList(pageindex, pagesize);
		List<Article> list = page.getContent();
		long totalCount = page.getTotalElements();
		int totalPage = page.getTotalPages();

		modelMap.addAttribute("datas", list);
		modelMap.addAttribute("totalCount", totalCount);
		modelMap.addAttribute("totalPage", totalPage);
		modelMap.addAttribute("pagesize", pagesize);
		modelMap.addAttribute("pageindex", pageindex);

		return "admin/Articlelist";
	}

	/**
	 * 获取文章列表
	 * 
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/getArticleList")
	public BaseVo<List<Article>> getArticleList(Integer pageindex, Integer pagesize) {
		pageindex = pageindex == null ? AdminConstants.DEF_PAGEINDEX : pageindex;
		pagesize = pagesize == null ? AdminConstants.DEF_PAGESIZE : pagesize;
		BaseVo<List<Article>> vo = new BaseVo<List<Article>>();
		Page<Article> page = articleService.getArticleList(pageindex, pagesize);
		List<Article> list = page.getContent();
		long totalCount = page.getTotalElements();
		int totalPage = page.getTotalPages();

		vo.setDatas(list);
		vo.setCurPage(pageindex);
		vo.setTotalCount(totalCount);
		vo.setTotalPage(totalPage);
		return vo;
	}

	/**
	 * 获取文章信息
	 * 
	 * @return
	 */
	@ResponseBody
	@GetMapping("/getArticleInfo")
	public BaseVo<Article> getArticleInfo(long id) {
		return null;
	}

	/**
	 * 获取文章信息
	 * 
	 * @return
	 */
	@GetMapping("/getArticle")
	public String updateArticle(ModelMap modelMap, long id) {
		Article oArticle = articleService.getArticleById(id);

		// 文章的附件
		Long appendixid = oArticle.getAppendixid();
		String file = systemConfig.getServerHost() + File.separator + "admin/images/default_Article.jpg";
		if (null != appendixid) {
			Appendix oAppendix = appendixService.getAppendix(appendixid);
			file = systemConfig.getServerHost() + File.separator
					+ FileUtil.getFilePathByFileName(oAppendix.getAppFile());
		}

		ArticleDTO dto = articleDOConvertDTO.convert(oArticle);
		dto.setFilename(file);

		modelMap.addAttribute("data", dto);
		return "admin/editArticle";
	}

	/**
	 * 删除案列
	 * 
	 * @return
	 */
	@ResponseBody
	@GetMapping("/deleteArticle")
	public BaseVo<Article> deleteArticle(long id) {
		BaseVo<Article> vo = new BaseVo<Article>();
		Article oArticle = articleService.getArticleById(id);
		if (null == oArticle) {
			logger.info("要删除的对象不存在，id=【" + id + "】");
			vo.setFailed("要删除的案列不存在！");
		}
		articleService.deleteArticle(oArticle);
		vo.setSuccessed("删除文章成功！");
		return vo;
	}

	/**
	 * 文章分类列表
	 * 
	 * @param modelMap
	 * @param pageindex
	 * @param pagesize
	 * @return
	 * @throws WebException
	 */
	@RequestMapping("/articletypelist")
	public String articleTypeList(ModelMap modelMap, @RequestParam(defaultValue = "0")Integer offset, Integer limit) throws WebException {
		Integer pageindex = offset == null ? AdminConstants.DEF_PAGEINDEX : offset;
		Integer pagesize = limit == null ? AdminConstants.DEF_PAGESIZE : limit;
		Page<ArticleType> page = articleService.getArticleTypeList(pageindex, pagesize);
		List<ArticleType> list = page.getContent();
		long totalCount = page.getTotalElements();
		int totalPage = page.getTotalPages();

		modelMap.addAttribute("datas", list);
		modelMap.addAttribute("totalCount", totalCount);
		modelMap.addAttribute("totalPage", totalPage);
		modelMap.addAttribute("pagesize", pagesize);
		modelMap.addAttribute("pageindex", pageindex);

		return "admin/articleTypeList";
	}

	@ResponseBody
	@PostMapping("/saveArticleType")
	public BaseVo<ArticleType> saveArticleType(@Valid ArticleTypeDTO oArticleTypeDTO) throws WebException {

		BaseVo<ArticleType> vo = new BaseVo<ArticleType>();

		ArticleType oArticleType = articleTypeDTOConvertDO.convert(oArticleTypeDTO);

		// 获取当前登录用户
		User curUser = UserUtil.getLoginUser();
		if (curUser == null) {
			throw new WebException("无法获取当前登录用户");
		}

		// 处理分类描述
		String desc = oArticleType.getTypedesc();
		if (StringUtil.isEmpty(desc)) {
			oArticleType.setTypedesc(oArticleType.getTypename());
		}

		oArticleType.setCrtime(new Date());

		oArticleType = articleService.saveArticleType(oArticleType);

		vo.setDatas(oArticleType);

		return vo;
	}

}
